package com.qing.shirodemo.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {



    @GetMapping(value = {"/","index"})
    public String index(){
        return "index";
    }


    @GetMapping(value = {"/user/add"})
    public String add(){
        return "/user/add";
    }


    @GetMapping(value = {"/user/update"})
    public String update(){
        return "/user/update";
    }

    @GetMapping("/tologin")
    public String  toLogin(){
        return "login";
    }

    @GetMapping("/loginout")
    public String  loginout(){
        Subject subject= SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    @GetMapping("/unauthorized")
    public String  unauthorized(){
        return "unauthorized";
    }


    @RequestMapping("login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model){
        //获取当前的用户
        Subject subject= SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        try{
            subject.login(token); //执行登录的方法，如果没有异常，说明OK
            return "index";
        }catch (UnknownAccountException e){
            //用户不存在
            model.addAttribute("msg","用户不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "login";
        }

    }
}
